package com.jm3.riscar3.memory;

import com.jm3.riscar3.helpers.BinaryTranslator;

public class StatusRegister extends Register {

	private boolean zeroFlag;
	private boolean carryFlag;
	private boolean negativeFlag;
	private boolean overflowFlag;
	
	public StatusRegister()
	{
		super();
		zeroFlag = carryFlag = negativeFlag = overflowFlag = false;
	}
	
	private String setCharAtPos(String str, char c,int pos)
	{
		String result = "";
		for(int i = 0; i < str.length(); i++)
		{
			if(i == pos)
				result += c;
			else
				result += str.charAt(i);
		}
		
		return result;
	}
	private void updateValue(boolean value, int position) throws Exception
	{
		int cData = this.readRegister();
		String binary = Integer.toBinaryString(cData);
		while(binary.length() < 4)
		{
			binary = "0" + binary;
		}
		
		if(value)
			binary = setCharAtPos(binary, '1', position);
		else
			binary = setCharAtPos(binary, '0', position);
		this.writeRegister(BinaryTranslator.getBitValue(binary));
			
	}
	
	public void setZeroFlag(boolean status) throws Exception
	{
		zeroFlag = status;
		updateValue(zeroFlag, 0);
	}
	
	public void setCarryFlag(boolean status) throws Exception
	{
		carryFlag = status;
		updateValue(carryFlag, 1);
	}
	
	public void setNegativeFlag(boolean status) throws Exception
	{
		negativeFlag = status;
		updateValue(negativeFlag, 2);
	}
	
	public void setOverflowFlag(boolean status) throws Exception
	{
		overflowFlag = status;
		updateValue(overflowFlag, 3);
	}
	
	public boolean getZeroFlag()
	{
		return zeroFlag;
	}
	
	public boolean getCarryFlag()
	{
		return carryFlag;
	}
	
	public boolean getNegativeFlag()
	{
		return negativeFlag;
	}
	
	public boolean getOverflowFlag()
	{
		return overflowFlag;
	}
	
}
